from Crypto.Hash import SHA
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
import base64

encode_utf8='utf-8'
key_num=1024

def rsa_creat_key():
    random_gr=Random.new().read#伪随机数
    rsa=RSA.generate(key_num,random_gr)#rsa实例
    private_pem=rsa.exportKey()#master密钥对
    #公私钥
    with open('private.pem','wb') as f:
        f.write(private_pem)

    public_pem=rsa.publickey().exportKey()
    with open('public.pem','wb') as f:
        f.write(public_pem)
   
#公钥加密
def rsa_enctrpt(message):
    with open('public.pem','rb') as f:
        key=f.read()
        rsakey=RSA.importKey(key) #导入公钥
        cipher=Cipher_pkcs1_v1_5.new(rsakey)#生成对象
        #加密明文，python3加密数据要是bytes不能str
        cipher_text=base64.b64encode(cipher.encrypt(
            message.encode(encoding=encode_utf8)))
        return cipher_text

#私钥解密
def rsa_decrypt(rsa_text):
    with open('private.pem','rb') as f:
        key=f.read()
    rsakey=RSA.importKey(key)
    cipher=Cipher_pkcs1_v1_5.new(rsakey)
    text=cipher.decrypt(base64.b64decode(rsa_text),"ERROR")
    return text.decode(encoding=encode_utf8)

#私钥签名
def rsa_sign(message):
    with open('private.pem','rb') as f:
        key=f.read()
    rsakey=RSA.importKey(key)
    signer=Signature_pkcs1_v1_5.new(rsakey)
    digest=SHA.new()
    digest.update(message.encode(encoding=encode_utf8))
    sign=signer.sign(digest)
    singnarure=base64.b64encode(sign)
    return singnarure

#公钥验证
def rsa_cheksign(message,signature):
    with open('public.pem','rb') as f:
        key=f.read()
    rsakey=RSA.importKey(key)
    verifier=Signature_pkcs1_v1_5.new(rsakey)
    digest=SHA.new()
    digest.update(message.encode(encoding=encode_utf8))
    is_verifier=verifier.verify(digest,base64.b64decode(signature))
    return is_verifier
                                
                            
